package com.gzx.spring.apis.utils;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Arrays;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson2.JSONObject;

public class JishuUtil {

	private String appId;
	private String appSecret;
	private String apiUrl;

	public JishuUtil appId(String appId) {
		this.appId = appId;
		return this;
	}

	public JishuUtil appSecret(String appSecret) {
		this.appSecret = appSecret;
		return this;
	}

	public JishuUtil apiUrl(String apiUrl) {
		this.apiUrl = apiUrl;
		return this;
	}

	public String md5(String input) throws Exception {
		// 创建MD5算法的MessageDigest实例
		MessageDigest md = MessageDigest.getInstance("MD5");

		// 将输入字符串转换为字节数组并进行MD5摘要计算
		byte[] messageDigest = md.digest(input.getBytes());

		// 将字节数组转换为十六进制字符串表示
		BigInteger no = new BigInteger(1, messageDigest);
		String hashtext = no.toString(16);

		// 如果十六进制字符串长度小于32位，在前面补0
		while (hashtext.length() < 32) {
			hashtext = "0" + hashtext;
		}

		return hashtext;
	}

	public String buildCustSign(JSONObject reqJson, String appSecret) throws Exception {
		reqJson.remove("sign");
		char[] charArray = JSONObject.toJSONString(reqJson).toCharArray();
		Arrays.sort(charArray);
		String signStr = new String(charArray);
		signStr = String.format("%s%s", signStr, appSecret);
		return md5(signStr);
	}

	private String exec(String pName, JSONObject reqJson) throws Exception, IOException, ClientProtocolException {
		RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)    // 连接超时：建立连接的最长时间
                .setSocketTimeout(5000)    // 读取超时：等待数据返回的最长时间
                .setConnectionRequestTimeout(3000)  // 连接池超时：从连接池获取连接的最长时间
                .build();
		
		CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
		// 2. 准备公共参数
		String timestamp = String.valueOf(Instant.now().toEpochMilli());

		// 3. 构建完整请求体
		JSONObject requestBody = new JSONObject();
		requestBody.put("appKey", appId);
		requestBody.put("pName", pName); // 根据文档，pName固定为demo
		requestBody.put("timestamp", timestamp);
		requestBody.put("reqJson", reqJson);
		String sign = buildCustSign(requestBody, appSecret);
		requestBody.put("sign", sign);

		// 4. 创建HTTP请求
		HttpPost httpPost = new HttpPost(apiUrl);
		httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
		httpPost.setEntity(new StringEntity(requestBody.toString(), StandardCharsets.UTF_8));

		// 5. 执行请求并处理响应
		CloseableHttpResponse response = httpClient.execute(httpPost);
		return EntityUtils.toString(response.getEntity());
	}

	public String ed006_v1(String id, String phone) throws Exception {
		// 1. 准备业务参数
		JSONObject reqJson = new JSONObject();
		reqJson.put("phoneMd5", md5(phone)); // 示例：手机号MD5
		reqJson.put("idNoMd5", md5(id)); // 可选：身份证MD5
		return exec("ed006_v1", reqJson);
	}

	public String edb003_v8(String name,String id, String phone) throws Exception {
		// 1. 准备业务参数
		JSONObject reqJson = new JSONObject();
		reqJson.put("phoneMd5", md5(phone));
		reqJson.put("idNoMd5", md5(id));
		reqJson.put("nameMd5", md5(name)); // 可选：姓名MD5
		return exec("edb003_v8", reqJson);
	}
}
